import { Outlet } from "react-router";
import { Link,Form } from "react-router";

import { getContacts } from "../data";
import type { Route } from "../+types/root";

import { createEmptyContact } from "../data";

export async function action() {
  const contact = await createEmptyContact()
  
  return {
    contact 
  }
}


export async function clientLoader() {
  // 将此方法的loader作为参数透传出去
  const contacts = await getContacts();

  return { contacts };
}

export default function SidebarLayout({ loaderData }:Route.ComponentProps) {
    const { contacts } = loaderData;

    return (
     <>
      <div id="sidebar">
        <h1>React Router Contacts</h1>
        <div>
          <Form id="search-form" role="search">
            <input
              aria-label="Search contacts"
              id="q"
              name="q"
              placeholder="Search"
              type="search"
            />
            <div aria-hidden hidden={true} id="search-spinner" />
          </Form>
          <Form method="post">
            <button type="submit">New</button>
          </Form>
        </div>
        <nav>
          {contacts.length ? (
            <ul>
              {contacts.map((contact) => (
                <li key={contact.id}>
                  <Link to={`contacts/${contact.id}`}>
                    {contact.first || contact.last ? (
                      <>
                        {contact.first} {contact.last}
                      </>
                    ) : (
                      <i>No Name</i>
                    )}
                    {contact.favorite ? (
                      <span>★</span>
                    ) : null}
                  </Link>
                </li>
              ))}
            </ul>
          ) : (
            <p>
              <i>No contacts</i>
            </p>
          )}
        </nav>
      </div>
      <div id="detail">
        <Outlet />
      </div>
    </>
  )
}
